package com.heima.search.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dtos.SearchArticleVo;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.service.SearchService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 基本搜索业务
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) {
        //创建请求
        SearchRequest request = new SearchRequest("app_info_article");
        //单字段查询
        request.source().query(QueryBuilders.matchQuery("title", dto.getSearchWords()));
        //高亮查询
        request.source().highlighter(new HighlightBuilder()
                .field("title")
                .preTags("<font style='color:red;font-size:inherit;'>")
                .postTags("</font>")
                .requireFieldMatch(false));
        //分页查询
        request.source().from(dto.getFromIndex()).size(dto.getPageSize());
        try {
            //解析响应结果
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            SearchHits hits = response.getHits();
            SearchHit[] searchHits = hits.getHits();
            List<SearchArticleVo> list = new ArrayList<>();
            if (searchHits != null && searchHits.length > 0) {
                for (SearchHit searchHit : searchHits) {
                    String sourceAsString = searchHit.getSourceAsString();
                    SearchArticleVo searchArticleVo = JSON.parseObject(sourceAsString, SearchArticleVo.class);
                    HighlightField highlightField = searchHit.getHighlightFields().get("title");
                    if (ObjectUtil.isNotEmpty(highlightField)) {
                        String string = highlightField.getFragments()[0].string();
                        //替换高亮字段
                        searchArticleVo.setH_title(string);
                    }
                    list.add(searchArticleVo);
                }
            }
            return ResponseResult.okResult(list);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseResult.okResult(null);
    }


    /**
     * 自动补全功能
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(UserSearchDto dto) {
        //TODO
        return null;
    }
}
